<template>
  <div class="video-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
    <!-- 返回按钮插槽 -->
    <slot name="back-button"></slot>

    <!-- 全屏视频播放器 -->
    <video
      ref="videoRef"
      class="video-player"
      :src="currentVideo?.videoUrl"
      loop
      muted
      playsinline
      preload="auto"
      @click="togglePlayPause"
      @loadstart="onVideoLoadStart"
      @canplay="onVideoCanPlay"
      @error="onVideoError"
    />

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p class="loading-text">加载中...</p>
    </div>

    <!-- 播放/暂停图标 -->
    <div v-if="showPlayIcon" class="play-icon-overlay">
      <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
    </div>

    <!-- 右侧操作按钮 -->
    <div class="action-buttons">
      <!-- 点赞 -->
      <div class="action-item" @click="toggleLike">
        <i :class="['action-icon', isLiked ? 'fas fa-heart liked' : 'far fa-heart']"></i>
        <span class="action-count">{{ likeCount }}</span>
      </div>

      <!-- 收藏 -->
      <div class="action-item" @click="toggleStar">
        <i :class="['action-icon', isStarred ? 'fas fa-star starred' : 'far fa-star']"></i>
        <span class="action-count">{{ starCount }}</span>
      </div>

      <!-- 评论 -->
      <div class="action-item" @click="showComments">
        <i class="action-icon fas fa-comment"></i>
        <span class="action-count">{{ commentCount }}</span>
      </div>
    </div>

    <!-- 底部视频信息 -->
    <div class="video-info">
      <div>
        <div class="author-info" v-if="currentVideo?.dramaTitle" @click="showAuthorModal">
          <span class="author-name">{{ currentVideo?.dramaTitle || '' }}</span>
          <i class="fa-solid fa-angle-right"></i>
        </div>

        <div class="video-meta" v-if="currentVideo?.drama?.actors?.length">
          <span
            class="bg-slate-400 rounded-md px-1 pt-1 pb-1 text-xs"
            v-for="(actor, index) in currentVideo?.drama?.actors?.slice(0, 2)"
            :key="index"
          >
            演员.{{ actor.name }}
          </span>
        </div>

        <p class="video-description ellipsis-2 mt-2">
          {{ currentVideo?.title || ''
          }}<span v-if="currentVideo?.description"> | {{ currentVideo?.description }}</span>
        </p>
      </div>

      <!-- 集数切换按钮 -->
      <div class="absolute -right-20 bottom-4">
        <button
          @click="$emit('toggle-episode-selector')"
          class="bg-black bg-opacity-50 text-white px-4 py-2 rounded-full text-sm hover:bg-opacity-70 transition-all"
        >
          <i class="fas fa-list mr-1"></i>
          {{ episodeButtonText }}
        </button>
      </div>
    </div>

    <!-- 抖音风格评论面板 -->
    <VideoCommentPanel
      :show="showCommentPanel"
      :video-id="String(currentVideo?.cid || '')"
      @close="closeCommentPanel"
      @comment-submitted="handleCommentSubmitted"
    />

    <!-- 视频信息弹框 -->
    <VideoInfoModal
      :show="showAuthorInfo"
      :video-data="currentVideo"
      :currentEpisodeIndex="currentEpisodeIndex"
      :flag="flag"
      @close="closeAuthorModal"
      @select-episode="selectEpisode"
    />

    <!-- 额外内容插槽 -->
    <slot name="extra-content"></slot>
  </div>
</template>

<script setup>
import VideoCommentPanel from '@/components/VideoCommentPanel.vue'
import VideoInfoModal from '@/components/VideoInfoModal.vue'

const props = defineProps({
  currentEpisodeIndex: {
    type: Number,
    default: 0
  },
  currentVideo: {
    type: Object,
    default: () => ({})
  },
  episodeButtonText: {
    type: String,
    default: '全集'
  },
  containerHeight: {
    type: String,
    default: 'calc(100vh - 114px)'
  },
  flag: {
    type: String,
    default: 'card'
  }
})

const emit = defineEmits([
  'next-video',
  'prev-video',
  'toggle-like',
  'toggle-star',
  'toggle-episode-selector',
  'comment-submitted',
  'select-episode'
])

// 视频相关状态
const videoRef = ref(null)
const isPlaying = ref(false)
const isLoading = ref(true)
const showPlayIcon = ref(false)

// 交互状态
const showCommentPanel = ref(false)
const showAuthorInfo = ref(false)

// 当前用户是否点赞
const isLiked = ref(false)
// 当前用户是否收藏
const isStarred = ref(false)
// 点赞数量
const likeCount = ref('0')
// 收藏数量
const starCount = ref('0')
// 评论数量
const commentCount = ref('0')

// 触摸相关
const touchStartY = ref(0)
const touchStartTime = ref(0)
const isVideoSwitching = ref(false)

/**
 * 播放/暂停切换
 */
const togglePlayPause = () => {
  if (!videoRef.value) return

  if (isPlaying.value) {
    videoRef.value.pause()
  } else {
    videoRef.value.play()
  }

  showPlayIcon.value = true
  setTimeout(() => {
    showPlayIcon.value = false
  }, 1000)
}

/**
 * 触摸开始
 */
const handleTouchStart = (e) => {
  touchStartY.value = e.touches[0].clientY
  touchStartTime.value = Date.now()
}

/**
 * 触摸移动
 */
const handleTouchMove = (e) => {
  e.preventDefault()
}

/**
 * 触摸结束
 */
const handleTouchEnd = (e) => {
  const touchEndY = e.changedTouches[0].clientY
  const touchDistance = touchStartY.value - touchEndY
  const touchDuration = Date.now() - touchStartTime.value

  // 有效滑动：距离大于50px且时间小于500ms
  if (Math.abs(touchDistance) > 50 && touchDuration < 500) {
    if (touchDistance > 0) {
      // 上滑 - 下一个视频
      emit('next-video')
    } else {
      // 下滑 - 上一个视频
      emit('prev-video')
    }
  }
}

/**
 * 点赞切换
 */
const toggleLike = () => {
  isLiked.value = !isLiked.value
  const count = parseInt(likeCount.value) || 0
  likeCount.value = (isLiked.value ? count + 1 : count - 1).toString()

  emit('toggle-like', { isLiked: isLiked.value, count: likeCount.value, currentVideo: props.currentVideo })
}

/**
 * 收藏切换
 */
const toggleStar = () => {
  isStarred.value = !isStarred.value
  const count = parseInt(starCount.value) || 0
  starCount.value = (isStarred.value ? count + 1 : count - 1).toString()

  emit('toggle-star', { isStarred: isStarred.value, count: starCount.value, currentVideo: props.currentVideo })
}

/**
 * 打开评论面板
 */
const showComments = () => {
  showCommentPanel.value = true
}

/**
 * 关闭评论面板
 */
const closeCommentPanel = () => {
  showCommentPanel.value = false
}

/**
 * 评论提交后处理
 */
const handleCommentSubmitted = (data) => {
  emit('comment-submitted', {
    ...data,
    video: props.currentVideo
  })
}

/**
 * 显示作者信息弹框
 */
const showAuthorModal = () => {
  showAuthorInfo.value = true
  console.log('显示作者信息弹框', props.currentVideo)
}

/**
 * 关闭作者信息弹框
 */
const closeAuthorModal = () => {
  showAuthorInfo.value = false
}

const selectEpisode = ({ episode, index }) => {
  emit('select-episode', { episode, index })
  closeAuthorModal()
}

/**
 * 视频事件处理
 */
const onVideoLoadStart = () => {
  isLoading.value = true
}

const onVideoCanPlay = () => {
  isLoading.value = false
  if (videoRef.value) {
    videoRef.value
      .play()
      .then(() => {
        isPlaying.value = true
      })
      .catch(() => {
        isPlaying.value = false
      })
  }
}

const onVideoError = () => {
  isLoading.value = false
  console.error('视频加载失败')
}

// 更新视频统计数据
const updateVideoStats = () => {
  const video = props.currentVideo
  if (video) {
    isLiked.value = video?.isLiked || false
    isStarred.value = video?.isFavorited || false
    likeCount.value = video?.likeCount || '0'
    starCount.value = video?.favoriteCount || '0'
    commentCount.value = video.commentCount || '0'

    // 重新加载视频
    if (videoRef.value) {
      isLoading.value = true
      videoRef.value.load()
    }
  }
}

// 监听视频播放状态
watch(
  () => videoRef.value,
  (newVal) => {
    if (newVal) {
      newVal.addEventListener('play', () => {
        isPlaying.value = true
      })
      newVal.addEventListener('pause', () => {
        isPlaying.value = false
      })
    }
  }
)

// 监听当前视频变化
watch(
  () => props.currentVideo,
  () => {
    updateVideoStats()
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  videoRef,
  isPlaying,
  isLoading
})
</script>

<style scoped>
.video-container {
  position: relative;
  width: 100vw;
  height: v-bind(containerHeight);
  background: #000;
  overflow: hidden;
  touch-action: pan-y;
  user-select: none;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #fff;
  margin-top: 16px;
  font-size: 14px;
}

.play-icon-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 15;
}

.play-icon-overlay i {
  color: #fff;
  font-size: 32px;
}

.action-buttons {
  position: absolute;
  right: 16px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  z-index: 10;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.action-icon {
  font-size: 32px;
  color: #fff;
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

.action-icon.liked {
  color: #ff4757;
}

.action-icon.starred {
  color: #ffa502;
}

.action-count {
  color: #fff;
  font-size: 12px;
  text-align: center;
}

.video-info {
  position: absolute;
  left: 16px;
  bottom: 20px;
  right: 80px;
  color: #fff;
  z-index: 10;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.author-info:hover {
  opacity: 0.8;
}

.author-name {
  font-weight: bold;
  font-size: 16px;
}

.video-description {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.video-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

/* 全屏弹框样式 */
.author-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.author-modal {
  background: #fff;
  width: 100%;
  max-width: 500px;
  margin: 0;
  position: fixed;
  bottom: 0;
  top: 0;
  max-height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: modalSlideIn 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
}

.modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #e9ecef;
  color: #333;
}

.modal-content {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.drama-info {
  text-align: left;
}

.drama-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.detail-item {
  margin-bottom: 16px;
}

.detail-item label {
  display: block;
  font-weight: 600;
  color: #555;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.actors-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.actor-tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
